package com.dede.state;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import com.dede.state.component.StateComponent;
import com.dede.state.component.SuccessComponent;

import java.util.List;

/**
 * StateLayout的代理类
 *
 * @author hsh
 *         2018/1/23 10:33.
 */
public class StateProxy {

    private final List<StateComponent> componentList;
    private final StateLayout stateLayout;
    private Converter converter;

    StateProxy(TargetContent targetContent, StateComponent.ReloadListener reloadListener, List<StateComponent> componentList) {
        ViewGroup parent = targetContent.getContentParent();
        View oldContent = targetContent.getOldContent();
        Context context = targetContent.getContext();
        this.componentList = componentList;

        /*
          将oldContent从parent中remove
          初始化StateLayout
          将oldContent add到StateLayout中
          将StateLayout add到parent中
        */
        ViewGroup.LayoutParams oldContentLayoutParams = oldContent.getLayoutParams();

        stateLayout = new StateLayout(context, reloadListener);
        if (parent != null) {
            parent.removeView(oldContent);
            parent.addView(stateLayout, targetContent.getChildIndex(), oldContentLayoutParams);
        }
        // 设置成功状态组件
        stateLayout.setSuccessComponent(new SuccessComponent(oldContent, context, reloadListener));

        initComponent();
    }

    /**
     * 初始化其他状态的页面
     */
    private void initComponent() {
        if (componentList != null) {
            for (StateComponent stateComponent : componentList) {
                stateLayout.addStateComponent(stateComponent);// 添加到map集合中
            }
        }
        stateLayout.showSuccess();// 默认显示成功状态
    }

    /**
     * 修改组件的布局，比如字体，颜色。。。
     *
     * @param clazz
     * @param transport
     * @return
     */
    public StateProxy customComponent(Class<? extends StateComponent> clazz, Transport transport) {
        stateLayout.customComponent(clazz, transport);
        return this;
    }

    /**
     * 设置组件转换器
     *
     * @param converter
     * @return
     */
    public StateProxy converter(Converter converter) {
        this.converter = converter;
        return this;
    }


    /**
     * 显示成功页面
     */
    public void showSuccess() {
        stateLayout.showSuccess();
    }

    /**
     * 显示其他状态
     *
     * @param stateClass
     */
    public void show(Class<? extends StateComponent> stateClass) {
        stateLayout.show(stateClass);
    }

    /**
     * 使用转换器显示
     * @param o
     */
    public void showWithConverter(Object o) {
        if (converter == null) {
            return;
        }

        Class<? extends StateComponent> stateComponentClass = converter.map(o);
        show(stateComponentClass);
    }

    /**
     * 获取当前的状态
     * @return
     */
    public View getStateLayout() {
        return stateLayout;
    }
}
